import React, { useState } from 'react';
import { Modal, Form, Input, DatePicker, message, Button } from 'antd';
import axios from 'axios';
import moment from 'moment';

const { RangePicker } = DatePicker;

const SignInTaskForm = ({ courseId, onSuccess, buttonText = "发起签到" }) => {
  const [form] = Form.useForm();
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);

  const showModal = () => {
    setVisible(true);
    // 设置默认值：当前时间到30分钟后
    form.setFieldsValue({
      timeRange: [moment(), moment().add(30, 'minutes')],
      description: '课堂签到'
    });
  };

  const handleCancel = () => {
    setVisible(false);
    form.resetFields();
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      const [startTime, endTime] = values.timeRange;
      
      // 构建请求数据
      const requestData = {
        course_id: courseId,
        class_ids: values.classIds,
        start_time: startTime.format('YYYY-MM-DD HH:mm:ss'),
        end_time: endTime.format('YYYY-MM-DD HH:mm:ss'),
        description: values.description || ''
      };

      console.log('创建签到任务请求数据:', requestData);

      // 发送请求创建签到任务
      const response = await axios.post('/teacher/sign_in/create', requestData);
      
      if (response.data && (response.data.code === 2000 || response.data.code === 0)) {
        message.success('创建签到任务成功');
        form.resetFields();
        handleCancel();
        if (onSuccess) {
          onSuccess(response.data.data);
        }
      } else {
        message.error(response.data?.message || '创建签到任务失败');
      }
    } catch (error) {
      console.error('创建签到任务错误:', error);
      message.error('创建签到任务失败: ' + (error.message || '未知错误'));
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      <Button type="primary" onClick={showModal}>
        {buttonText}
      </Button>
      <Modal
        title="创建签到任务"
        open={visible}
        onOk={handleOk}
        onCancel={handleCancel}
        confirmLoading={loading}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="timeRange"
            label="签到时间范围"
            rules={[{ required: true, message: '请选择签到时间范围' }]}
          >
            <RangePicker 
              showTime 
              format="YYYY-MM-DD HH:mm:ss"
            />
          </Form.Item>
          <Form.Item
            name="description"
            label="签到描述"
          >
            <Input placeholder="请输入签到描述" />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default SignInTaskForm; 